<template>
  <el-dialog
    v-el-drag-dialog
    title="安检隐患"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <div class="app-page">
      <aside-tree
        title="安检隐患级别"
        :tree-data="treeData"
        :mouse-button="false"
        node-key="keyVal"
        :loading="$loadingPlugin.getTreeData"
        @currentChange="currentChange"
        @refresh="getTreeData"
      />
      <div class="content">
        <div class="top-box">
          <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
          <el-checkbox v-model="checked">app端显示红色字体</el-checkbox>
        </div>
        <div>
          <lb-table
            ref="lbTable"
            align="center"
            element-loading-text="加载中"
            :column="column"
            :data="tableData.data"
          />
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AsideTree from '@/views/components/OrgTree'
  import { formatColumnMap } from '@/utils'
  import { checkConfigHiddenRank, checkConfigInquire, checkConfigHiddenRankList, checkConfigHiddenRankSave } from '@/api'

  export default {
    name: 'hidden',
    components: {
      AsideTree
    },
    data() {
      return {
        visible: false,
        checked: false,
        current: {},
        treeData: [],
        newCradData: {},
        newTreeData: {},
        checkMapeList: [], // 随单安检项
        chooseList: [], // 安检选项
        tableData: {
          data: []
        },
        checkList1: [], // 随单安检
        checkList2: [] // 定期安检
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'checkType',
            label: '安检类型',
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.checkType === 1 ? '随单安检' : row.checkType === 2 ? '定期安检' : ''}</span>
                : <el-select v-model={ row.checkType } onChange={(val) => this.change(val, row)}>
                <el-option label= { '随单安检' } value={ 1 } />
                <el-option label= { '定期安检' } value={ 2 } />
              </el-select>
              )
            }
          },
          {
            prop: 'itemName',
            label: '安检项',
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.itemName ? row.itemName : row.itemId && formatColumnMap(this.checkMapeList, 'itemId', row.itemId, 'itemName') }</span>
                : <el-select v-model={row.itemId} placeholder={ '请选择' } onChange={(val) => this.changeMape(val, row)}>
                    {
                      this.checkMapeList.map(item => {
                        return <el-option key={item.itemId} label= { item.itemName } value={ item.itemId } />
                      })
                    }
                  </el-select>
              )
            }
          },
          {
            prop: 'csmName',
            label: '安检选项',
            render: (h, { row, $index }) => {
              return (
                row.isEdit ? <span>{row.itemDetailName ? row.itemDetailName : row.itemDetailId && formatColumnMap(this.chooseList, 'itemDetailId', row.itemDetailId, 'itemDetailName')}</span>
                : <el-select v-model={row.itemDetailId} placeholder={ '请选择' }>
                    {
                      this.chooseList.map(item => {
                        return <el-option key={item.itemDetailId} label= { item.itemDetailName } value={ item.itemDetailId } />
                      })
                    }
                  </el-select>
              )
            }
          },
          {
            prop: 'csmName',
            label: '操作',
            render: (h, { row, $index }) => {
              return (
                <div>
                  { row.isEdit === true && <el-link size='mini' onClick={() => this.onEdit(row, $index)}>编辑</el-link> }
                  { row.isEdit === false && <el-link size='mini' onClick={() => this.onSave(row)}>保存</el-link> }
                  <el-link size='mini' onClick={() => this.onDel(row, $index)}>删除</el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {},
    methods: {
      open(cardVal, treeVal) {
        this.newCradData = cardVal
        this.newTreeData = treeVal
        this.getTreeData(cardVal, treeVal)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async success() {
        const flag = this.tableData.data.every(item => item.itemDetailId && item.isEdit === true)
        if (flag) {
          this.tableData.data = this.tableData.data.map(item => {
            item.sp = this.checked ? 1 : 0
            return { ...item }
          })
          console.log('保存入参', this.tableData.data)
          const { status } = await checkConfigHiddenRankSave(this.tableData.data)
          console.log('保存成功', status)
          if (status === 200) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.visible = false
          }
        } else {
          this.$message({
            message: '表格中存在未结束编辑数据',
            type: 'warning'
          })
        }
      },
      reset() {
        this.tableData.data = []
        this.checkList1 = []
        this.checkList2 = []
      },
      // 增加
      add() {
        const addData = {
          csmType: this.newCradData.value,
          checkType: '',
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          isEdit: true,
          orgSNNo: this.newTreeData.orgSNNo,
          warnLevel: this.current.keyVal, // 安全级别
          itemId: '',
          itemDetailId: '',
          sp: this.checked ? 1 : 0
        }
        this.tableData.data.push(addData)
        console.log('增加以后的数据', this.tableData.data)
      },
      async currentChange(current) {
        // 安全级别
        this.current = current
        // 判断是否存在某个属性
        const flag1 = this.tableData.data.every(item => !item.isEdit)
        if (flag1) {
          if (current.keyVal) {
            await this.getHiddenApi(current)
          } else {
            this.$message({
              message: '请选择安检隐患级别',
              type: 'warning'
            })
          }
        } else {
          // 判断是否有未编辑状态
          const flag2 = this.tableData.data.every(item => item.isEdit === false)
          if (flag2) {
            this.$message({
              message: '表格中存在未结束编辑数据',
              type: 'warning'
            })
          } else {
            // 判断是新数据还是老数据
            const flag = this.tableData.data.every(item => item.itemName)
            const flag1 = !this.tableData.data.length && !flag ? true : !!(this.tableData.data.length && flag)
            if (flag1) {
              // 老数据
              await this.getHiddenApi(current)
            } else {
              // 新数据
              this.$confirm('切换安全隐患,是否保存当前编辑隐患级别?', '操作提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$message({
                  message: '表格中存在未结束编辑数据',
                  type: 'warning'
                })
              }).catch(async() => {
                this.tableData.data = []
                // 再次请求接口
                await this.getHiddenApi(current)
              })
            }
          }
        }
      },
      async getHiddenApi(current) {
        // 随单安检
        const res = await checkConfigInquire({
          csmType: this.newCradData.value,
          checkType: 1,
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          orgSNNo: this.newTreeData.orgSNNo
        })
        this.checkList1 = res.data
        const { data } = await checkConfigHiddenRankList({
          warnLevel: current.keyVal,
          orgId: this.newTreeData.orgId,
          orgSNNo: this.newTreeData.orgSNNo,
          csmType: this.newCradData.value
        })
        // 是否可编辑
        const isEdit = true
        this.tableData.data = data.map(item => {
          return { ...item, isEdit }
        })
        if (this.tableData.data.length) {
          this.checked = this.tableData.data[0].sp === 1
        }
        // 定期安检
        const res1 = await checkConfigInquire({
          csmType: this.newCradData.value,
          checkType: 2,
          orgId: this.newTreeData.orgId,
          orgName: this.newTreeData.orgName,
          orgSNNo: this.newTreeData.orgSNNo
        })
        this.checkList2 = res1.data
      },
      // 安检类型
      change(val, row) {
        this.tableData.data.map(item => {
          if (item.itemId === row.itemId) {
            item.itemId = ''
            item.itemDetailId = ''
          }
        })
        this.checkMapeList = []
        this.checkMapeList = val === 1 ? this.checkList1 : this.checkList2
      },
      // 编辑
      onEdit(val) {
        // 判断是否其他项正在编辑
        const obj = this.tableData.data.filter(item => item.isEdit === false)
        if (obj.length) {
          if (obj[0].checkType === '' || obj[0].itemId === '' || obj[0].itemDetailId === '') {
            this.$message({
              message: `${obj[0].checkType === '' ? '请选择安检类型' : obj[0].itemId === '' ? '请选择安检项' : obj[0].itemDetailId === '' ? '请选择安检选项' : ''}`,
              type: 'warning'
            })
          } else {
            if (obj[0].itemId === val.itemId) {
              val.isEdit = true
            } else {
              obj[0].isEdit = true
              val.isEdit = false
            }
          }
        } else {
          val.isEdit = false
        }
        this.checkMapeList = val.checkType === 1 ? this.checkList1 : this.checkList2
      },
      // 删除
      onDel(val, index) {
        this.tableData.data.splice(index, 1)
        console.log('this.tableData.data', this.tableData.data)
      },
      // 保存
      onSave(val) {
        // 判断是否其他项正在编辑
        const obj = this.tableData.data.filter(item => item.isEdit === false)
        if (obj.length) {
          if (obj[0].checkType === '' || obj[0].itemId === '' || obj[0].itemDetailId === '') {
            this.$message({
              message: `${obj[0].checkType === '' ? '请选择安检类型' : obj[0].itemId === '' ? '请选择安检项' : obj[0].itemDetailId === '' ? '请选择安检选项' : ''}`,
              type: 'warning'
            })
          } else {
            if (obj[0].itemId === val.itemId) {
              val.isEdit = true
            } else {
              obj[0].isEdit = true
              val.isEdit = false
            }
          }
        } else {
          val.isEdit = false
        }
        console.log('保存以后的数据', this.tableData.data)
      },
      // 安检项
      changeMape(val, row) {
        this.tableData.data.map(item => {
          if (item.itemDetailId === row.itemDetailId) {
            item.itemDetailId = ''
          }
        })
        const arr = this.checkMapeList.filter(item => item.itemId === val)
        this.chooseList = arr[0].detailList
      },
      async getTreeData(cardVal, treeVal) {
        const res = await checkConfigHiddenRank({
          page: cardVal.id,
          csmType: cardVal.value,
          orgId: treeVal.orgId
        })
        const data = res.data.map(item => ({
          label: item.keyName,
          ...item
        }))
        this.treeData = data
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding-top: 0;
  padding-left: 0;
  margin-top: 0;
}
.app-page {
  display: flex;
  padding: 0;
  .content {
    flex: 1;
    width: 0;
    padding: 10px 10px 0 10px;
    overflow: auto;
    .top-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;
    }
  }
}
</style>
